package com.liuc.practice.login.interceptor;


import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

/**
 * @Author Liu Chang
 * @Date 2021/9/19 1:18 上午
 */
public class RequestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        HttpSession session = request.getSession();
        Enumeration<String> attributeNames = session.getAttributeNames();
        
        while (attributeNames.hasMoreElements()) {
            String key = attributeNames.nextElement().toString();
            String value = (String)session.getAttribute(key);
            System.out.println("key = " + key + ", value = " + value);
        }

        String username = (String)session.getAttribute("username");
        String context = request.getContextPath();
        if (username == null) {
            response.sendRedirect(context + "/login");
            return false;
        } else {
            response.sendRedirect(context + "/success");
            return true;
        }
    }
}
